package camera;

import coordinates.MeanDetector;
import java.util.logging.Level;
import java.util.logging.Logger;
import objectExtraction.ColourDetector;
import com.googlecode.javacv.FrameGrabber.Exception;
import static com.googlecode.javacv.cpp.opencv_core.*;
import com.googlecode.javacv.*;
import com.googlecode.javacv.cpp.opencv_calib3d.*;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

public class ColorMeanCamera extends Camera {

    final int INTERVAL = 10;// 1sec
//    static CvScalar rgba_min = cvScalar(0, 0, 130, 0);// RED wide dabur birko
//    static CvScalar rgba_max = cvScalar(80, 80, 255, 0);
    ColourDetector colDet = new ColourDetector();
    MeanDetector meanDet = new MeanDetector();
    IplImage image;
    FrameGrabber grabber;
    public IplImage imTemp, detectThrs, tempTh;

    public ColorMeanCamera(int camera, int fov, int IMAGE_NO) {
        super(camera, fov);
        this.IMAGE_NO = IMAGE_NO;
    }

    @Override
    public void run() {
        grabber = new VideoInputFrameGrabber(CAMERA_NUM);
        int posX, posY;
        try {
            System.out.println("CAme"+CAMERA_NUM);
            grabber.start();
            Thread.sleep(1000);
            IplImage img;
            while (active) {
                img = grabber.grab();
                imTemp = img.clone();
                if (img != null) {

                    detectThrs = colDet.getThresholdImage(img);
                    tempTh = detectThrs.clone();

                    posX = meanDet.getMeanX(detectThrs);
                    posY = meanDet.getMeanY();

                    CvPoint start = new CvPoint(posX, 0);
                    CvPoint end = new CvPoint(posX, detectThrs.width());
                    System.out.println("Camera"+CAMERA_NUM+"  "+posY);
                    if (posY > last_Y[CAMERA_NUM]) {
                      //  System.out.println("Came");
                        if (posX > 0) {
                            cvDrawLine(imTemp, start, end, CvScalar.RED, 4, 8, 0);
                        }
                        theta = angFind.angleFinder(posX, detectThrs.width(), CAMERA_FOV);
                        cvReleaseImage(detectThrs);
                    } else {
                        theta = 0;
                        cvReleaseImage(detectThrs);
                    }
                }
            }
            grabber.stop();
        } catch (InterruptedException ex) {
            Logger.getLogger(ColorMeanCamera.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception e) {
            System.out.println("Exception in Color Mean Detector");
            e.printStackTrace();
        }
    }
}
